package com.enjoy.webservice;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Client {

    public static void main(String[] args) throws IOException {
        //第一步：创建服务地址，不是WSDL地址
        URL url = new URL("http://127.0.0.1:8085/serverCase");
        //2：打开到服务地址的一个连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //3：设置连接参数
        //3.1设置发送方式：POST必须大写
        connection.setRequestMethod("POST");
        //3.2设置数据格式：Content-type
        connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
        //3.3设置输入输出，新创建的connection默认是没有读写权限的，
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //4.组织SOAP协议数据，发送给服务端
        String soapXML = getXML("bob");
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());

        //5：接收服务端的响应
        int responseCode = connection.getResponseCode();
        if (200 == responseCode) {
            //表示服务端响应成功
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String temp;

            while (null != (temp = br.readLine())) {
                sb.append(temp);
            }

            System.out.println(sb);

            is.close();
            isr.close();
            br.close();
        }

        os.close();
    }


    public static String getXML(String name) {
        return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.enjoy.com/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <web:getValue>\n" +
                "         <!--Optional:-->\n" +
                "         <arg0>" + name + "</arg0>\n" +
                "      </web:getValue>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
    }

}
